<template>
  <div>
    <header>
      <h1>实验室节能系统</h1>
    </header>
  <div class="login-card">
  <div class="card-header">
    <div class="log">登录</div>
  </div>
  <form ref="loginForm">
    <div class="form-group">
      <label for="username">用户名:</label>
      <input ref="username" name="username" id="username" type="text">
    </div>
    <div class="form-group">
      <label for="password">密码:</label>
      <input ref="password" name="password" id="password" type="password" autocomplete="current-password">
    </div>
    <div class="form-group">
      <input value="Login" type="submit">
    </div>
  </form>
</div>
</div>
</template>

<script>
import axios from 'axios';
import store from '../store';
export default {
  
  name: 'UserLogin',
  mounted() {
    this.$refs.loginForm.addEventListener('submit', this.handleSubmit);
  },
    methods: {
      handleSubmit(event) {
      event.preventDefault(); // 阻止表单的默认提交行为
      this.login();
    },
    login() {
  const username = this.$refs.username.value;
  const password = this.$refs.password.value;

  axios.post('/api-login/login', {
    username: username,
    password: password
  })
  .then(response => {
  if (response.data.token) {
    // 更新VueX中的认证状态和令牌
    store.dispatch('setAuth', { isAuthenticated: true, token: response.data.token });
    // 重定向到主页
    this.$router.push({ name: 'page' });
  } else {
    alert('Login failed');
  }
})
  .catch((error) => {
  console.error('Error:', error);
  if (error.response && error.response.status === 401) {
    alert('用户名或密码错误，请重试！');
  } else {
    console.error('An error occurred:', error);
    alert('An unexpected error occurred. Please try again.');
  }
  });
}
  }
}
</script>

<style lang="less">

header{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 0.7rem;
    padding: 0 20px;
    width: 100%;
    h1{
      font-size:0.6rem;
      color:#fff;
      text-align:center;
      line-height:1rem;
    }
  }
.login-card {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  background-color: #e8e8e8;
  box-shadow: 2px 2px 10px #ccc;
}

.card-header {
  text-align: center;
  margin-bottom: 20px
}

.card-header .log {
  margin: 0;
  font-size: 24px;
  color: black;
}

.form-group {
  margin-bottom: 15px;
}

label {
  font-size: 18px;
  margin-bottom: 5px;
}

input[type="text"], input[type="password"] {
  width: 100%;
  padding: 12px 20px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  transition: 0.5s;
}

input[type="submit"] {
  width: 100%;
  background-color: #333;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type="submit"]:hover {
  background-color: #ccc;
  color: black;
}

</style>
  